﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

namespace AbingtonBooks.Pages.Profile.MyBooks
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["Customer"] == null)
            {
                Response.Redirect("~/Pages/UnauthorizedAccess");
            }

            if (!IsPostBack)
            {
                using (dbAbingtonBooks context = new dbAbingtonBooks())
                {
                    Customer thisCustomer = (Customer)Session["Customer"];
                    var data = context.getCustomerBooks(thisCustomer.CustomerId);
                    if (data != null)
                    {
                        BookGrid.DataSource = data;

                        BookGrid.DataBind();

                    }
                    else
                    {

                    }
                }
            }
            

        }
            
        
        protected void removeBook(object sender, CommandEventArgs e)
        {
            using (dbAbingtonBooks context = new dbAbingtonBooks())
            {
                int BookId = Convert.ToInt32(e.CommandArgument);
                int imgId = (int)context.Books.Where(b => b.BookId == BookId).Select(b => b.ImageId).First();
                string imgSource = context.Images.Where(i => i.ImageId == imgId).Select(i => i.Src).First();
                if (File.Exists(Server.MapPath(imgSource)))
                {
                    File.Delete(Server.MapPath(imgSource));
                }
                context.removeBookByBookId(BookId);
                Response.Redirect("~/Pages/Profile/MyBooks");
            }
        }

    }
}